import request from '@/utils/request'
import { getLocalChannels, hasToken, setLocalChannels } from '@/utils/storage'
import { ArticlePayload, Channel, HomeAction, MoreAction } from '../reducers/home'
import { RootThunkAction } from '../index'
/**
 * 获取用户的频道列表
 * @returns
 */
export const getUserChannels = (): RootThunkAction => {
  return async (dispatch) => {
    // 判断用户是否登录
    if (hasToken()) {
      // 登录了，发送请求获取数据，并且保存到本地
      const res = await request({
        method: 'GET',
        url: 'user/channels',
      })
      dispatch(saveChannels(res.data.channels))
    }
    // 没有登录，但是本地有数据
    const channels = getLocalChannels()
    if (channels) {
      // 渲染本地数据
      dispatch(saveChannels(channels))
    } else {
      // 没有token，也没有本地数据
      const res = await request({
        method: 'GET',
        url: 'user/channels',
      })
      dispatch(saveChannels(res.data.channels))
      // 把数据存到本地
      setLocalChannels(res.data.channels)
    }
  }
}
// 保存用户的频道列表
export const saveChannels = (payload: Channel[]): HomeAction => {
  // console.log(payload);
  return {
    type: 'home/userChannels',
    payload,
  }
}
/**
 * 获取所有频道列表数据
 * @returns
 */
export const getAllChannels = (): RootThunkAction => {
  return async (dispatch) => {
    const res = await request({
      method: 'GET',
      url: '/channels',
    })
    // console.log(res);
    dispatch(saveAllChannels(res.data.channels))
  }
}
// 保存所有频道
export const saveAllChannels = (payload: Channel[]): HomeAction => {
  return {
    type: 'home/allChannels',
    payload,
  }
}
/**
 * 删除频道
 * @param {*} channel
 * @returns
 */
export const delChannles = (channel: Channel): RootThunkAction => {
  return async (dispatch, getState) => {
    const { userChannels } = getState().home
    // console.log(getState());
    //判断是否登录
    // 如果登录了，就改变后台的值，和redux中的数据
    if (hasToken()) {
      // 发请求删除，并且改变redux中的值、
      await request({
        method: 'DELETE',
        url: `/v1_0/user/channels/${channel.id}`,
      })
      // console.log(res);
      dispatch(
        saveChannels(
          userChannels.filter((item) => {
            return item.id !== channel.id
          })
        )
      )
    } else {
      // 没有登录，操作本地
      setLocalChannels(
        userChannels.filter((item) => {
          return item.id !== channel.id
        })
      )
      dispatch(
        saveChannels(
          userChannels.filter((item) => {
            return item.id !== channel.id
          })
        )
      )
    }
  }
}
/**
 * 添加频道
 * @param {*} channel
 * @returns
 */
export const addChannel = (channel: Channel): RootThunkAction => {
  return async (dispatch, getState) => {
    const channels = [...getState().home.userChannels, channel]
    if (hasToken()) {
      // 发请求添加
      await request.patch('/user/channels', {
        channels: [channel],
      })
      dispatch(saveChannels(channels))
    } else {
      dispatch(saveChannels(channels))
      setLocalChannels(channels)
    }
  }
}
/**
 * 获取频道列表数据
 * @param {*} param0
 * @returns
 */
export const getArticleList = (channelId: number, timestamp: string, loadMore = false): RootThunkAction => {
  return async (dispatch) => {
    const res = await request({
      url: '/articles',
      method: 'GET',
      params: {
        channel_id: channelId,
        timestamp,
        loadMore,
      },
    })
    // console.log(res);
    dispatch(
      setArticleList({
        channelId,
        timestamp: res.data.pre_timestamp,
        list: res.data.results,
        loadMore,
      })
    )
  }
}
// 保存频道列表数据
export const setArticleList = (payload: ArticlePayload): HomeAction => {
  return {
    type: 'home/setChannelsList',
    payload,
  }
}
export const setMoreAction = (payload: MoreAction): HomeAction => {
  return {
    type: 'home/moreAction',
    payload,
  }
}
